using System;
using AutoMapper;
using K9Nano.Dependency;
using K9Nano.MultiTenancy;
using K9Nano.Runtime;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using TestBase;
using Xunit.Abstractions;

namespace EFCoreTest
{
    public class EfCoreTestBase : IDisposable
    {
        protected TestDbContext Context => ServiceProvider.GetRequiredService<TestDbContext>();
        protected readonly ITestOutputHelper Logger;
        protected readonly IServiceProvider ServiceProvider;

        public EfCoreTestBase(ITestOutputHelper testOutputHelper)
        {
            // builder.UseLoggerFactory(loggerFactory);
            var services = new ServiceCollection()
                .AddK9NanoCore(null)
                .AddDistributedMemoryCache()
                .AddAutoMapper(GetType().Assembly)
                .AddTransient<ITenantStore, NullTenantStore>()
                .AddK9NanoMemoryCache()
                .AddEfCore<TestDbContext>(builder =>
                {
                    //builder.UseMySql(
                    //    "server=localhost;User ID=root;Password=1234;database=k9nano;Charset=utf8;Allow User Variables=true",
                    //    mySqlOptions =>
                    //    {
                    //        mySqlOptions.ServerVersion(new Version(10, 3, 13),
                    //            ServerType.MariaDb); // replace with your Server Version and Type
                    //    });
                    builder.UseInMemoryDatabase("unittest");
                })
                .AddLogging(builder => { builder.AddProvider(new XunitLoggerProvider(testOutputHelper)); });
            services.RegisterConventionalAssembly(GetType().Assembly);

            ServiceProvider = services.BuildServiceProvider(); ;
            Logger = testOutputHelper;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}